package org.vacoor.xqq.core.util;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Regexs {

    /**
     * IP v4 块 eg: 255
     */
    public static final String IPV4_BLOCK_REGEX = "^(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])$";

    /**
     * IP v4 eg: 192.168.1.1
     */
    public static final String IPV4_REGEX = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

    private Regexs() {
    }


    /**
     * 测试 source 是否与给定正则匹配
     */
    public static boolean matches(CharSequence source, String regex) {
        return getPattern(regex).matcher(source).matches();
    }

    public static Pattern getPattern(String regex) {
        return Pattern.compile(regex);
    }

    /**
     * 获取捕获组捕获的内容
     */
    public static String[][] grep(String source, String pattern) {
        List<String[]> result = new ArrayList<String[]>();

        Matcher matcher = getPattern(pattern).matcher(source);
        while (matcher.find()) {
            int gc = matcher.groupCount();

            String[] m = new String[gc + 1];
            for (int i = 0; i <= gc; i++) {
                m[i] = matcher.group(i);
            }
            result.add(m);
        }
        return result.toArray(new String[result.size()][]);
    }
}
